<?php


namespace app\api\service;


use think\Exception;

class AccessToken{
    private $appId;
    private $secretId;
    private $access_token_url;
    const TOKEN_CACHED_KEY = 'template_access_token';
    const TOKEN_EXPIRE_IN = 7199;

    public function __construct(){
        $this->appId = config('wx.appId');
        $this->secretId = config('wx.secretId');
        $this->access_token_url  = sprintf(config('wx.access_token_url'),$this->appId,$this->secretId);
    }

    //不写入缓存中,生成的token保存到文件中
    public function getTokens(){
        $path = ROOT_PATH.'public/access_token.txt';
        if(is_file($path)){
            $result = json_decode(file_get_contents($path),true);
            if(time() > $result['expires_in']){
                return $this->getAccessTokens();
            }else{
                return $result['access_token'];
            }
        }else{
           return $this->getAccessTokens();
        }
    }

    private function getAccessTokens(){
        $result = https_request($this->access_token_url);
        $result = json_decode($result,true);
        if (!$result)
        {
            throw new Exception('获取AccessToken异常');
        }
        if(!empty($result['errcode'])){
            throw new Exception($result['errmsg']);
        }
        //将生成的token保存起来
        $result['expires_in'] = time() + $result['expires_in'];
        file_put_contents(ROOT_PATH.'public/access_token.txt',json_encode($result));
        return $result['access_token'];
    }

    //从缓存中取
    public function getToken(){
        $token = cache(self::TOKEN_CACHED_KEY);
        if($token){
            return $token;
        }
        return $this->getAccessToken();
    }

    private function getAccessToken(){
        $result = https_request($this->access_token_url);
        $result = json_decode($result,true);
        if (!$result)
        {
            throw new Exception('获取AccessToken异常');
        }
        if(!empty($result['errcode'])){
            throw new Exception($result['errmsg']);
        }
        //将生成的token保存起来
        cache(self::TOKEN_CACHED_KEY,$result['access_token'],self::TOKEN_EXPIRE_IN);
        return $result['access_token'];
    }







}
















